﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using WHC.Security.BLL;
using WHC.Security.Entity;
using WHC.OrderWater.Commons;
using WeifenLuo.WinFormsUI.Docking;

namespace WHC.Security.UI
{
    public partial class FrmOU : DockContent
    {
        private OU ou = new OU();
        private string currentID = string.Empty;

        public FrmOU()
        {
            InitializeComponent();
        }

        private void FrmOU_Load(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void RefreshTreeView()
        {
            treeView1.Nodes.Clear();
            treeView1.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;

            this.cmbUpperOU.Items.Clear();
            this.cmbUpperOU.Items.Add(new CListItem("无","-1"));

            List<OUInfo> list = ou.GetAll();
            foreach (OUInfo info in list)
            {
                this.cmbUpperOU.Items.Add(new CListItem(info.Name, info.ID.ToString()));

                if (info.PID != -1)
                {
                    continue;
                }

                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.Name;
                item.Tag = info.Name;
                this.treeView1.Nodes.Add(item);

                AddChildNode(list, item);
            }

            Cursor.Current = Cursors.Default;
            treeView1.EndUpdate();
            this.treeView1.ExpandAll();
        }
        private void RefreshRoles(int id)
        {
            this.lvwRole.Items.Clear();
            Role role = new Role();
            foreach (RoleInfo info in role.GetRolesByOU(id))
            {
                CListItem item = new CListItem(info.Name, info.ID.ToString());
                this.lvwRole.Items.Add(item);
            }
            if (this.lvwRole.Items.Count > 0)
            {
                this.lvwRole.SelectedIndex = 0;
            }
        }

        private void RefreshUsers(int id)
        {
            this.lvwUser.Items.Clear();
            User user = new User();
            foreach (UserInfo info in user.GetUsersByOU(id))
            {
                string name = string.Format("{0}（{1}）", info.Name, info.FullName);
                CListItem item = new CListItem(name, info.ID.ToString());
                this.lvwUser.Items.Add(item);
            }
            if (this.lvwUser.Items.Count > 0)
            {
                this.lvwUser.SelectedIndex = 0;
            }
        }

        private void AddChildNode(List<OUInfo> list, TreeNode fnode)
        {
            foreach (OUInfo info in list)
            {
                if (info.PID != int.Parse(fnode.Name))
                {
                    continue;
                }
                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.Name;
                item.Tag = info.Name;
                fnode.Nodes.Add(item);

                AddChildNode(list, item);
            }
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeNode node = treeView1.GetNodeAt(e.X, e.Y);
                if (node != null)
                {
                    treeView1.SelectedNode = node;
                }
            }

            base.OnMouseDown(e);
        }

        private void menu_Delete_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && !string.IsNullOrEmpty(node.Name))
            {
                if (MessageUtil.ShowYesNoAndTips("您确认删除吗?") == DialogResult.Yes)
                {
                    try
                    {
                        ou.Delete(node.Name);
                        RefreshTreeView();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        MessageUtil.ShowError(ex.Message);
                    }
                }
            }
        }

        private void menu_Add_Click(object sender, EventArgs e)
        {
            ClearInput();
            currentID = "";
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && node.Tag != null)
            {
                int index = this.cmbUpperOU.FindString(node.Tag.ToString());
                this.cmbUpperOU.SelectedIndex = index;
            }

            this.txtName.Focus();
        }

        private void ClearInput()
        {
            this.txtName.Text = "";
            this.txtNote.Text = "";
            this.txtAddress.Text = "";
            this.cmbUpperOU.SelectedIndex = 0;
            this.lvwRole.Items.Clear();
            this.lvwUser.Items.Clear();
        }

        private OUInfo SetOUInfo(OUInfo info)
        {
            info.Name = this.txtName.Text;
            info.Note = this.txtNote.Text;
            info.Address = this.txtAddress.Text;

            CListItem item = this.cmbUpperOU.SelectedItem as CListItem;
            info.PID = Convert.ToInt32(item.Value);

            return info;
        }

        private void menu_Update_Click(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void menu_ExpandAll_Click(object sender, EventArgs e)
        {
            this.treeView1.ExpandAll();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                string id = e.Node.Name;
                OUInfo info = (OUInfo)ou.FindByID(id);

                if (info != null)
                {
                    currentID = id.ToString();

                    this.txtName.Text = info.Name;
                    this.txtNote.Text = info.Note;
                    this.txtAddress.Text = info.Address;

                    OUInfo info2 = (OUInfo)ou.FindByID(info.PID.ToString());
                    if (info2 != null)
                    {
                        int index = this.cmbUpperOU.FindString(info2.Name);
                        this.cmbUpperOU.SelectedIndex = index;
                    }
                    else
                    {
                        int index = this.cmbUpperOU.FindString("无");
                        this.cmbUpperOU.SelectedIndex = index;
                    }

                    int intID = Convert.ToInt32(id);
                    RefreshUsers(intID);
                    RefreshRoles(intID);
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            #region 验证用户输入
            if (this.txtName.Text == "")
            {
                MessageUtil.ShowTips("机构名称不能为空");
                this.txtName.Focus();
                return;
            }

            #endregion

            if (!string.IsNullOrEmpty(currentID))
            {
                int id = Convert.ToInt32(currentID);
                try
                {
                    OUInfo info = ou.FindByID(currentID) as OUInfo;
                    if (info != null)
                    {
                        info = SetOUInfo(info);
                        ou.Update(info, info.ID.ToString());

                        RefreshTreeView();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
            else
            {
                string filter = string.Format("Name='{0}' ", this.txtName.Text);
                bool isExist = ou.IsExistRecord(filter);
                if (isExist)
                {
                    MessageUtil.ShowTips("组织机构名称已存在！");
                    this.txtName.Focus();
                    return;
                }

                OUInfo info = new OUInfo();
                info = SetOUInfo(info);

                try
                {
                    ou.Insert(info);
                    RefreshTreeView();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
        }

        private void btnEditUser_Click(object sender, EventArgs e)
        {
            if (this.treeView1.SelectedNode != null)
            {
                FrmEditTree dlg = new FrmEditTree();
                dlg.OUID = currentID;
                dlg.DisplayType = FrmEditTree.DisplayTreeType.User;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    this.RefreshUsers(Convert.ToInt32(currentID));
                }
            }
            else
            {
                MessageUtil.ShowTips("请选择具体的机构");
            }
        }

        private void DeleteUser(int OUID, int UserID)
        {
            new OU().RemoveUser(UserID, OUID);
            this.RefreshUsers(OUID);
        }

        private void btnRemoveUser_Click(object sender, EventArgs e)
        {
            if (this.lvwUser.SelectedItem != null)
            {
                CListItem userItem = this.lvwUser.SelectedItem as CListItem;
                if (userItem != null)
                {
                    int userId = Convert.ToInt32(userItem.Value);
                    if (!string.IsNullOrEmpty(currentID))
                    {
                        int ouID = Convert.ToInt32(currentID);
                        DeleteUser(ouID, userId);
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            menu_Add_Click(null, null);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            menu_Delete_Click(null, null);
        }
    }
}
